import React, { useEffect, useState } from "react";
import { Button, Card, Form, Input, Select, Table } from "antd";
import { SearchOutlined } from "@ant-design/icons";
import {
  reqCityOrCounty,
  reqHosList,
  reqHosStatus,
  reqProvince,
} from "@/api/hospitalList";
import type {
  provinceListType,
  hosDataListType,
  hosDataListItemType,
} from "@/api/hospitalList";
import { useNavigate } from "react-router-dom";

interface searchParamsType {
  cityCode?: string;
  districtCode?: string;
  hoscode?: string;
  hosname?: string;
  hostype?: string;
  provinceCode?: string;
  status?: number;
}
export default function HospitalList() {
  const [form] = Form.useForm();
  const navigate = useNavigate();
  //数据1:总条数
  const [total, setTotal] = useState(0);
  //数据2:当前页
  const [current, setCurrent] = useState(1);
  //数据3:每页条数
  const [pageSize, setPageSize] = useState(3);
  //数据4:省份列表
  const [provinceList, setProvinceList] = useState<provinceListType>([]);
  //数据5:城市列表
  const [cityList, setCityList] = useState<provinceListType>([]);
  //数据6:区县列表
  const [countyList, setCountyList] = useState<provinceListType>([]);
  //数据7：医院列表
  const [hospitalList, setHospitalList] = useState<hosDataListType>([]);
  //数据8：是否加载中
  const [isLoading, setIsLoading] = useState(false);
  //数据9: 医院类型列表(因为和选择城市公用接口，所以还是使用选择城市的类型)
  const [hosTypeList, setHosTypeList] = useState<provinceListType>([]);
  //数据10:查询时的参数对象
  const [searchParams, setSearchParams] = useState<searchParamsType>({});

  //方法1:省份列表下拉选择的事件回调函数(select的onChange回调函数的参数就是选中的option的value值)
  const provinceChange = async (value: string) => {
    //清空城市和区县的选择
    form.setFieldsValue({ cityCode: undefined, districtCode: undefined });
    //发送城市的请求
    const result = await reqCityOrCounty(value);
    setCityList(result);
  };

  //方法2:城市列表下拉选择的事件回调函数
  const cityChange = async (value: string) => {
    //清空区县的选择
    form.setFieldsValue({ districtCode: undefined });
    //发送城市的请求
    const result = await reqCityOrCounty(value);
    setCountyList(result);
  };

  //方法3：请求医院列表数据
  const getHosList = async () => {
    //设置正在加载
    setIsLoading(true);

    const result = await reqHosList({
      page: current,
      limit: pageSize,
      ...searchParams,
    });
    console.log(result, "result");
    //设置医院列表
    setHospitalList(result.content);
    //设置数据总数
    setTotal(result.totalElements);

    //设置加载完成
    setIsLoading(false);
  };

  //方法4:页码改变的事件回调函数
  const pageOnChange = (current: number, pageSize: number) => {
    // console.log(current, pageSize);
    setCurrent(current);
    setPageSize(pageSize);
  };

  //方法5:表单被提交事件
  const formFinish = (value: any) => {
    // console.log(value, "value");
    setSearchParams(value);
  };

  //方法6:查看医院详情
  const showDetail = (id: string) => {
    return () => {
      navigate(`/syt/hospital/hosDetail`, {
        state: {
          id,
        },
      });
    };
  };

  //方法7:排班按钮
  const schedule = (hoscode: string) => {
    return () => {
      navigate(`/syt/hospital/hosSchedule/${hoscode}`);
    };
  };

  //方法8:改变以上上下线状态
  const changeStatus = (id: string, oldStatus: number) => {
    return async () => {
      await reqHosStatus(id, oldStatus === 1 ? 0 : 1);

      //重新请求列表
      getHosList();
    };
  };

  //初始化:请求省份
  useEffect(() => {
    const getProvince = async () => {
      const result = await reqProvince();
      setProvinceList(result);
    };
    getProvince();
  }, []);

  //初始化:请求医院列表
  useEffect(() => {
    getHosList();
  }, [current, pageSize, searchParams]);

  //初始化：请求医院类型(后台偷懒了，还是用请求区县的接口，固定传入10000参数即可获取)
  useEffect(() => {
    const getHosTypeList = async () => {
      const result = await reqCityOrCounty("10000");
      setHosTypeList(result);
    };
    getHosTypeList();
  }, []);

  const columns = [
    {
      title: "序号",
      render(_: any, __: any, index: number) {
        return index + 1;
      },
    },
    {
      title: "医院logo",
      dataIndex: "logoData",
      //如果当前没有书写dataIndex属性,则参数拿到的是当前完整的数据
      //如果当前书写了dataIndex属性,则参数拿到的是这个dataIndex属性代表的值
      render(row: any) {
        return (
          <img
            src={"data:image/jpge;base64," + row}
            style={{ width: "100px" }}
          />
        );
      },
    },
    {
      title: "医院名称",
      dataIndex: "hosname",
    },
    {
      title: "等级",
      dataIndex: "param",
      render(param: any) {
        return param.hostypeString;
      },
    },
    {
      title: "详细地址",
      dataIndex: "param",
      render(param: any) {
        return param.fullAddress;
      },
    },
    {
      title: "状态",
      dataIndex: "status",
      render(status: any) {
        return status ? "上线" : "下线";
      },
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
    },
    {
      title: "操作",
      width: "270px",
      render(row: hosDataListItemType) {
        return (
          <div>
            <Button
              type="primary"
              style={{ marginRight: "10px" }}
              onClick={showDetail(row.id)}
            >
              查看
            </Button>
            <Button
              type="primary"
              style={{ marginRight: "10px" }}
              onClick={schedule(row.hoscode)}
            >
              排班
            </Button>
            <Button type="primary" onClick={changeStatus(row.id, row.status)}>
              {row.status === 0 ? "上线" : "下线"}
            </Button>
          </div>
        );
      },
    },
  ];
  return (
    <Card>
      <Form layout="inline" form={form} onFinish={formFinish}>
        <Form.Item name="provinceCode">
          <Select
            placeholder="请选择省份"
            style={{ width: "200px", marginBottom: "20px" }}
            onChange={provinceChange}
          >
            {provinceList.map((item) => {
              return (
                <Select.Option value={item.value} key={item.id}>
                  {item.name}
                </Select.Option>
              );
            })}
          </Select>
        </Form.Item>
        <Form.Item name="cityCode">
          <Select
            placeholder="请选择城市"
            style={{ width: "200px", marginBottom: "20px" }}
            onChange={cityChange}
          >
            {cityList.map((item) => {
              return (
                <Select.Option value={item.value} key={item.id}>
                  {item.name}
                </Select.Option>
              );
            })}
          </Select>
        </Form.Item>
        <Form.Item name="districtCode">
          <Select
            placeholder="请选择区县"
            style={{ width: "200px", marginBottom: "20px" }}
          >
            {countyList.map((item) => {
              return (
                <Select.Option value={item.value} key={item.id}>
                  {item.name}
                </Select.Option>
              );
            })}
          </Select>
        </Form.Item>
        <Form.Item name="hosname">
          <Input
            placeholder="医院名称"
            style={{ width: "200px", marginBottom: "20px" }}
          />
        </Form.Item>
        <Form.Item name="hoscode">
          <Input
            placeholder="医院编号"
            style={{ width: "200px", marginBottom: "20px" }}
          />
        </Form.Item>
        <Form.Item name="hostype">
          <Select
            placeholder="医院类型"
            style={{ width: "200px", marginBottom: "20px" }}
          >
            {hosTypeList.map((item) => {
              return (
                <Select.Option value={item.value} key={item.id}>
                  {item.name}
                </Select.Option>
              );
            })}
          </Select>
        </Form.Item>
        <Form.Item name="status">
          <Select
            placeholder="医院状态"
            style={{ width: "200px", marginBottom: "20px" }}
          >
            <Select.Option value={1}>上线</Select.Option>
            <Select.Option value={0}>下线</Select.Option>
          </Select>
        </Form.Item>
        <Form.Item>
          <Button
            icon={<SearchOutlined />}
            type="primary"
            style={{ marginRight: "20px" }}
            htmlType="submit"
          >
            查询
          </Button>
          <Button
            onClick={() => {
              //清空表单
              form.resetFields();
              //清空数据 让医院列表重新查询展示
              setSearchParams({});
            }}
          >
            清空
          </Button>
        </Form.Item>
      </Form>
      <Table
        loading={isLoading}
        columns={columns}
        dataSource={hospitalList}
        rowKey={(row) => row.id}
        bordered
        pagination={{
          //数据总数
          total: total,
          //当前页码
          current: current,
          //每页条数
          pageSize: pageSize,
          //是否展示pageSize选择器
          showSizeChanger: true,
          //pageSize选择器的选项
          pageSizeOptions: [3, 5, 7, 10],
          //页码改变的事件回调函数
          onChange: pageOnChange,
        }}
      ></Table>
    </Card>
  );
}
